package com.pkx.guide.fcms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pkx.guide.common.util.DateUtils;
import com.pkx.guide.common.util.IpUtils;
import com.pkx.guide.common.util.StringUtils;
import com.pkx.guide.fcms.selector.FcmsPlayItemSelector;
import com.pkx.guide.fcms.service.FcmsPlayItemService;
import com.pkx.guide.fcms.service.FcmsPlayService;
import com.pkx.guide.info.entity.TInfoGuide;
import com.pkx.guide.info.entity.TInfoGuidePlayItem;
import com.pkx.guide.info.entity.TInfoGuidePlayList;
import com.pkx.guide.info.entity.TInfoGuideStatus;
import com.pkx.guide.info.service.TInfoGuidePlayListService;
import com.pkx.guide.info.service.TInfoGuideService;
import com.pkx.guide.info.service.TInfoGuideStatusService;
import com.pkx.guide.record.entity.TRecordGuideStatus;
import com.pkx.guide.record.service.TRecordGuideStatusService;
import com.sansi.fcms.devinfor.DeviceControl;
import com.sansi.fcms.devinfor.DeviceVar;
import com.sansi.playlist.AreaItem;
import com.sansi.playlist.PageItem;
import com.sansi.playlist.PlayItem;
import com.sansi.playlist.entry.*;
import com.sansi.playlist.fcms.PlayListFcms;
import com.sansi.tools.RetrunData;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * 播放表生成业务
 */
@Service
public class FcmsPlayServiceImpl implements FcmsPlayService {

    @Value("${playList.file.path}")
    private String playListFilePath;

    @Value("${playList.file.suffix}")
    private String playListFileSuffix;

    @Value("${playList.file.bmp}")
    private String playListFileBmp;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    @Resource
    private FcmsPlayItemSelector fcmsPlayItemSelector;

    @Resource
    private TInfoGuideService guideService;

    @Resource
    private TInfoGuideStatusService infoGuideStatusService;

    @Resource
    private TRecordGuideStatusService recordGuideStatusService;

    /**
     * 生成播放表
     * @return
     */
    @Override
    public TInfoGuidePlayList createFcmsPlayList(TInfoGuidePlayList tInfoGuidePlayList){
        if (tInfoGuidePlayList == null){
            throw new IllegalArgumentException("参数为空");
        }
        if (tInfoGuidePlayList.getGuidePlayItem() == null){
            throw new IllegalArgumentException("播放项不可为空");
        }
        // String name = tInfoGuidePlayList.getName() + playListFileSuffix;
        String name = tInfoGuidePlayList.getName();
        String url = playListFilePath + name;
        Animation animation = new Animation();
        animation.setInAnimation(tInfoGuidePlayList.getInAnimation());
        animation.setInAnimationSpeed(tInfoGuidePlayList.getInAnimationSpeed());
        int index = 1;

        // 播放项信息
        TInfoGuidePlayItem guidePlayItem = tInfoGuidePlayList.getGuidePlayItem();

        // 展示图片信息
        PictureBase pictureBase = null;
        if (StringUtils.isNotEmpty(guidePlayItem.getPictureName())){
            pictureBase = new PictureBase(guidePlayItem.getPictureType(), guidePlayItem.getPictureName());
        }

        // 展示文字信息
        TextBase textBase = null;
        if (StringUtils.isNotEmpty(guidePlayItem.getText())){
            String[] fontColourArr = new String[5];
            if (StringUtils.isEmpty(guidePlayItem.getFontColour())){
                fontColourArr = new String[]{"128", "0", "0", "0", "0"};
            } else {
                fontColourArr = guidePlayItem.getFontColour().split(",");
            }
            BaseColour fontColour = new BaseColour(Integer.parseInt(fontColourArr[0]),Integer.parseInt(fontColourArr[1]),Integer.parseInt(fontColourArr[2]),Integer.parseInt(fontColourArr[3]),Integer.parseInt(fontColourArr[4]));
            textBase = new TextBase(guidePlayItem.getTextType(),guidePlayItem.getText());
            // 字体大小，如果显示屏支持矢量字库，则字体大小可以自由设置
            // 如果显示屏只支持点阵字库，则字体大小取值有效范围：(16,16)、(24,24)、(32,32)；(48,48)或(64,64) )二者选一 ；(96,96) 超大屏可能支持
            // 备注：字号是否支持可以进行赋值尝试，然后观察显示屏是否显示，如果不显示则表示该值不支持。
            textBase.setFontSize(guidePlayItem.getFontSize());
            // fontName 字体名称，目前只支持：h（黑体）、k（楷体）、s（宋体）、f（仿宋体）等四种字体，其它值均为非法值
            textBase.setFontName(guidePlayItem.getFontName());
            textBase.setFontColour(fontColour);
            textBase.setWordSpace(guidePlayItem.getWordSpace());
        }

        // 播放时间信息
        PlayTimeBase playTime = new PlayTimeBase(guidePlayItem.getPlayTotalTime());

        // 设置播放表内播放项信息
        String id = UUID.randomUUID().toString().replace("-", "");
        String itemName = "ITEM" + tInfoGuidePlayList.getName() + "0" + index;
        PlayItem playItem = new PlayItem();
        playItem.setPlayNo(1);
        playItem.setId(id);
        playItem.setName(itemName);
        if (pictureBase != null){
            playItem.setPictureBase(pictureBase);
            playItem.setMaterialType(2);
        }
        if (textBase != null){
            playItem.setTextBase(textBase);
            playItem.setMaterialType(1);
        }
        playItem.setPlayTime(playTime);
        playItem.setAnimation(animation);
        playItem.setX(guidePlayItem.getPlayItemX());
        playItem.setY(guidePlayItem.getPlayItemY());

        //播放项集合
        List<PlayItem> playItemList1 = new ArrayList<>();
        playItemList1.add(playItem);

        String[] backColourArr = new String[5];
        if (StringUtils.isEmpty(tInfoGuidePlayList.getBackgroundColour())){
            backColourArr = new String[]{"255", "255", "255", "255", "255"};
        } else {
            backColourArr = tInfoGuidePlayList.getBackgroundColour().split(",");
        }
        // 显示屏背景颜色
        Background background = new Background();
        BaseColour backColour = new BaseColour(Integer.parseInt(backColourArr[0]),Integer.parseInt(backColourArr[1]),Integer.parseInt(backColourArr[2]),Integer.parseInt(backColourArr[3]),Integer.parseInt(backColourArr[4]));
        background.setBackColour(backColour);
        // 显示屏区域1
        AreaPositon areaPositon1 = new AreaPositon(tInfoGuidePlayList.getArea1X(),tInfoGuidePlayList.getArea1Y(),tInfoGuidePlayList.getArea1Height(),tInfoGuidePlayList.getArea1Width(),1);
        String areaId1 = UUID.randomUUID().toString().replace("-", "");
        String areaName1 = "AREA" + tInfoGuidePlayList.getName();
        AreaItem areaItem1 = new AreaItem(areaId1, areaName1, areaPositon1, playItemList1);
        areaItem1.setBackground(background);
        // 显示屏区域列表
        List<AreaItem> areaItemList = new ArrayList<>();
        areaItemList.add(areaItem1);
        // 显示屏页面
        String pageId = UUID.randomUUID().toString().replace("-", "");
        String pageName = "PAGE" + tInfoGuidePlayList.getName();
        PageItem pageItem = new PageItem(pageId, pageName, areaItemList);

        PlayListFcms plf = new PlayListFcms();
        // 生成播放表
        plf.createFcmsPlayList(url, pageItem);

        tInfoGuidePlayList.setName(name);
        tInfoGuidePlayList.setPlayListUrl(url);
        tInfoGuidePlayList.setAreaId(areaId1);
        tInfoGuidePlayList.setAreaName(areaName1);
        tInfoGuidePlayList.setPageId(pageId);
        tInfoGuidePlayList.setPageName(pageName);
        return tInfoGuidePlayList;
    }

    /**
     * 初始化设备
     * @param guide
     * @return
     */
    @Override
    public RetrunData deviceInforInit(TInfoGuide guide){
        // 每次程序启动是都必须首先进行初始化。
        return DeviceVar.deviceInforInit(guide.getDeviceId(),1, guide.getGuidIp(), Integer.parseInt(guide.getGuidPort()),2048);
    }

    /**
     * 获取显示屏当前亮度和调节模式
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsLightAndModeQurey(TInfoGuide guide){
        // 初始化设备
        deviceInforInit(guide);
        // 读取调节模式和亮度值
        return DeviceControl.fcmsLightAndModeQurey(guide.getDeviceId());
    }

    /**
     * 设置显示屏亮度和调节模式
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsLightAndModeSet(TInfoGuide guide){
        // 初始化设备
        deviceInforInit(guide);
        //设置调节模式和亮度值
        guideService.modify(guide);
        return DeviceControl.fcmsLightAndModeSet(guide.getDeviceId(), guide.getLightMode(), guide.getLightVal());
    }

    /**
     * 读取显示屏本地时间
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsTimeRead(TInfoGuide guide){
        // 初始化设备
        deviceInforInit(guide);
        return DeviceControl.fcmsTimeRead(guide.getDeviceId());
    }

    /**
     * 设置显示屏本地时间
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsTimeSet(TInfoGuide guide){
        // 初始化设备
        deviceInforInit(guide);
        return DeviceControl.fcmsTimeSet(guide.getDeviceId());
    }

    /**
     * 向显示屏设备上传文件(仅素材)
     * @param guide
     * @param tInfoGuidePlayItem
     * @return
     */
    @Override
    public RetrunData fcmsUploadFile(TInfoGuide guide, TInfoGuidePlayItem tInfoGuidePlayItem){
        // 初始化设备
        deviceInforInit(guide);
        //上传文件
        return DeviceControl.fcmsUploadFile(guide.getDeviceId(), tInfoGuidePlayItem.getPictureUrl(),tInfoGuidePlayItem.getPictureName());
    }

    /**
     * 向显示屏设备上传播放表
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsUploadPlayList(TInfoGuide guide){
        // 初始化设备
        deviceInforInit(guide);
        // 如果播放项包含图片，同时上传图片
        if (guide.getGuidePlayList() != null && guide.getGuidePlayList().getGuidePlayItem() != null){
            if (StringUtils.isNotEmpty(guide.getGuidePlayList().getGuidePlayItem().getPictureUrl())
                    && StringUtils.isNotEmpty(guide.getGuidePlayList().getGuidePlayItem().getPictureName())){
                DeviceControl.fcmsUploadFile(guide.getDeviceId(), guide.getGuidePlayList().getGuidePlayItem().getPictureUrl(),guide.getGuidePlayList().getGuidePlayItem().getPictureName());
            }
        }
        // 上传播放表
        return DeviceControl.fcmsUploadPlayList(guide.getDeviceId(), guide.getGuidePlayList().getPlayListUrl());
    }


    /**
     * 激活播放表
     * @param guide
     * @return
     */
    @Override
    public RetrunData fcmsActivePlayList(TInfoGuide guide, String playListName){
        // 初始化设备
        deviceInforInit(guide);
        // 激活播放表
        return DeviceControl.fcmsActivePlayList(guide.getDeviceId(), playListName);
    }

    /**
     * 读取显示屏当时显示画面
     * @param guide
     * @return
     */
    @Override
    public String fcmsNowPictureQuery(TInfoGuide guide){
        // 生成文件名（包含路径）
        String fileName = guide.getDeviceId() + ".bmp";
        String filePath = playListFileBmp + fileName;
        // 初始化设备
        deviceInforInit(guide);
        DeviceControl.fcmsNowPictureQuery(guide.getDeviceId(),filePath);
        // 返回url路径
        return domain + localFilePrefix + "/bmp/" + fileName;
    }

    /**
     * 读取所有显示屏当时显示画面
     * @return
     */
    @Override
    public Boolean fcmsNowPictureQueryAll(){
        /*List<TInfoGuide> guideList = guideService.list(new QueryWrapper<TInfoGuide>().lambda().eq(TInfoGuide::getDelFlg, 0));
        if (guideList == null || guideList.size() == 0){
            return false;
        }
        TInfoGuideStatus infoGuideStatus = null;
        TRecordGuideStatus recordGuideStatus = null;
        String currentTimeStr = DateUtils.getCurrentTimeStr();
        for (TInfoGuide guide : guideList) {
            if (StringUtils.isEmpty(guide.getGuidIp())){
                continue;
            }
            infoGuideStatus = new TInfoGuideStatus();
            recordGuideStatus = new TRecordGuideStatus();
            // 是否可以ping通
            boolean result = IpUtils.ping(guide.getGuidIp());
            infoGuideStatus.setGuideId(guide.getId());
            infoGuideStatus.setGuidIp(guide.getGuidIp());
            infoGuideStatus.setOfflineTime(currentTimeStr);
            infoGuideStatus.setOfflineStatus(result? "0": "1");
            *//*infoGuideStatus.setPictureUrl("");
            // 查询情报板显示内容
            if (result){
                String pictureUrl = fcmsNowPictureQuery(guide);
                infoGuideStatus.setPictureUrl(pictureUrl);
            }*//*
            // 保存或更新情报板状态信息
            // infoGuideStatusService.saveOrUpdateGuideStatus(infoGuideStatus);
            // 保存记录
            // BeanUtils.copyProperties(infoGuideStatus, recordGuideStatus);
            // recordGuideStatusService.saveTRecordGuideStatus(recordGuideStatus);
        }*/
        return true;
    }
}
